package net.caixiaomi.info.util;

import android.os.Environment;

import net.caixiaomi.info.app.CommonApp;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 */
public class FileHelper {

    private static String folderName;

    public static void initFolderName(String fName) {
        folderName = Environment.getExternalStorageDirectory() + "/" + fName;
    }

    public static File folderName() {
        File file = new File(folderName);
        if (!file.exists())
            file.mkdir();
        return file;
    }

    private static String getPng(String path) {
        return path + ".png";
    }

    public static String generateFileName(String packageName) {
        return getPng(packageName);
    }

    public static File generateFile(String path) {
        File file = new File(folderName, ".nomedia");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                file.mkdir();
            }
        }
        return new File(folderName(), generateFileName(path));
    }

    /**
     * 返回SD卡根路径
     *
     * @return
     */
    public static String getSdcardRoot() {

        String retDir = "";
        try {
            File dir = isSdcardReady() ? Environment.getExternalStoragePublicDirectory(Constants.ROOT_FILE) : CommonApp.getInstance().getExternalFilesDir(Constants.ROOT_FILE);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            retDir = dir.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            retDir = "";
        }
        return retDir;
    }

    /**
     * 判断SD卡是否存在
     *
     * @return
     */
    public static boolean isSdcardReady() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    public static File getOutputMediaFile() {

        File mediaStorageDir = new File(getSdcardRoot(), Constants.DIR_FILE_TEMP_PIC);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(mediaStorageDir.getPath()).append(File.separator).append(Constants.IMG_PER).append(timeStamp).append(System.currentTimeMillis()).append(".jpg");
        String name = stringBuilder.toString();
        File mediaFile = new File(name);

        return mediaFile;
    }

}
